package com.LeetCode.Math;

import org.junit.Test;

import java.util.LinkedList;
import java.util.Queue;
import java.util.Stack;

/**
 * 后缀表达式求值
 */
public class PostfixValue {



    public  int postfixValue(String postfix){
        Stack<Integer> stack = new Stack<>();
        int ans = 0;
        for(int i = 0; i<postfix.length(); i++){
            char c = postfix.charAt(i);
            if(c>='0' && c<='9'){
                stack.push(c-'0');
            }else{
                int opt1 = stack.pop();
                int opt2 = stack.pop();
                switch (c){
                    case '+' : {
                        stack.push(opt2 + opt1);
                        break;
                    }
                    case '-' : {
                        stack.push(opt2 - opt1);
                        break;
                    }
                    case '*' : {
                        stack.push(opt2 * opt1);
                        break;
                    }
                    case '/' : {
                        stack.push(opt2 / opt1);
                        break;
                    }
                }
            }
        }
        ans = stack.size() == 0 ? 0 : stack.pop();
        return ans;
    }

    @Test
    public void test(){
        String pattern = "34+5*6-";
        System.out.println(postfixValue(pattern));
    }
}
